import json
from dashscope import TextEmbedding
from dashvector import Client, Doc
import uuid
import dashscope


def generate_embeddings(text_list):
    rsp = TextEmbedding.call(model=TextEmbedding.Models.text_embedding_v1, input=text_list)
    embeddings = [record['embedding'] for record in rsp.output['embeddings']]
    return embeddings


def process_and_insert_data(collection_name, data, batch_size, endpoint, Material_uuid=None):
    # 设置 API 密钥
    dashscope.api_key = 'sk-39e47712f94a4816a18f356dd26aa1c8'
    client = Client(
        api_key='sk-hz4xtal1OMo24Ft7hLC1EQdSZimEw6918B4CE47C911EF90AA2A0812EF32E2',
        endpoint=endpoint
    )

    try:
        # 创建或获取集合
        collection = client.get(collection_name)
        material_uuid = str(uuid.uuid4())
        assert collection, f"Failed to retrieve collection '{collection_name}'"
        results = []
        batch_docs = [data]

        for docs in batch_docs:
            try:
                text_content = docs['text_content']
                Id = docs['Material_id']
                material_id = material_uuid
                material_url = docs['Material_url']

                if 'Video_length' in docs:
                    video_length = docs['Video_length']
                    docs_to_insert = [
                        Doc(id=material_id, vector=generate_embeddings([text_content])[0],
                            fields={
                                "text_content": text_content,
                                "Material_url": material_url,
                                "Video_length": video_length,
                                "Material_id": Id
                            })
                    ]
                elif 'audio_length' in docs:
                    audio_length = docs['audio_length']
                    docs_to_insert = [
                        Doc(id=material_id, vector=generate_embeddings([text_content])[0],
                            fields={
                                "text_content": text_content,
                                "Material_url": material_url,
                                "audio_length": audio_length,
                                "Material_id": Id
                            })
                    ]
                else:
                    docs_to_insert = [
                        Doc(id=material_id, vector=generate_embeddings([text_content])[0],
                            fields={
                                "text_content": text_content,
                                "Material_url": material_url,
                                "Material_id": Id
                            })
                    ]

                rsp = collection.insert(docs_to_insert)

                if not rsp:

                    # print(f"Failed to insert batch: {material_id}")
                    results.append(
                        {"code": 1, "msg": f"Failed to insert batch: {material_id}", "requests_id": rsp.request_id,
                         "output": rsp.output})

                else:
                    # print(f"Successfully inserted batch: {material_id}")
                    results.append(
                        {"code": 0, "msg": f"Successfully inserted batch: {material_id}", "requests_id": rsp.request_id,
                         "output": rsp.output})
            except Exception as e:
                # print(f"Error processing batch: {e}")
                results.append({"code": 1, "msg": f"Error processing batch: {e}"})

            return results  # 在循环结束后返回结果列表
    except Exception as e:
        # print(f"Error during processing: {e}")
        return {"code": 1, "msg": f"Error during processing: {e}"}
